package myStack;

public class MySequeStack<T> {
    final int initCapacity = 10;        //顺序栈的初始容量(常量)
    private int capacity;            //存放顺序栈的容量
    private T[] data;            //存放顺序栈中元素
    private int top;            //存放栈顶指针

    public MySequeStack()        //构造方法，实现data和size初始化
    {
        data = (T[]) new Object[initCapacity];  //强制转换为E类型数组
        capacity = initCapacity;
        top = -1;
    }

    private void updatecapacity(int newcapacity)    //改变栈容量
    {
        T[] newdata = (T[]) new Object[newcapacity];    //newcapacity≥top+1
        for (int i = 0; i <= top; i++)    //复制原来的元素
            newdata[i] = data[i];
        capacity = newcapacity;        //设置新容量
        data = newdata;            //仍由data标识数组
    }
    //栈的基本运算算法

    public boolean empty()    //判断栈是否为空
    {
        return top == -1;
    }

    public void push(T e)            //元素e进栈
    {
        if (top == capacity - 1)        //顺序栈空间满时倍增容量
            updatecapacity(2 * (top + 1));
        top++;                //栈顶指针增1
        data[top] = e;
    }

    public T pop()                        //出栈操作
    {
        if (empty())
            throw new IllegalArgumentException("栈空");
        T e = (T) data[top];
        top--;
        if (top + 1 > initCapacity && top + 1 == capacity / 4)  //满足条件容量减半
            updatecapacity(capacity / 2);
        return e;
    }

    public T peek()        //取栈顶元素操作
    {
        if (empty())
            throw new IllegalArgumentException("栈空");
        return (T) data[top];
    }


}
